/*
 * @Author: 抱着羊啃 1437670973@qq.com
 * @Date: 2025-10-21 13:53:36
 * @LastEditors: 抱着羊啃 1437670973@qq.com
 * @LastEditTime: 2025-10-27 22:54:17
 * @FilePath: \fall-guard-band\src\main\java\com\example\fall_guard_band\controller\UserController.java
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package com.example.fall_guard_band.controller;

import com.example.fall_guard_band.pojo.dto.*;
import com.example.fall_guard_band.pojo.entity.User;
import com.example.fall_guard_band.pojo.result.Result;
import com.example.fall_guard_band.service.UserService;
import com.example.fall_guard_band.utils.JwtUtil;
import com.example.fall_guard_band.properties.JwtProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@Slf4j
@RequiredArgsConstructor
public class UserController {

    @Autowired
    private final UserService userService;

    @Autowired
    private JwtProperties jwtProperties;



    @PostMapping("/login")
    public Result<UserLoginDTO> login(@RequestBody LoginRequest req) {
        if (req == null || isBlank(req.getUsername()) || isBlank(req.getPassword()) || req.getNursingHomeId() == null) {
            return Result.error("参数不完整：请提供用户名、密码和养老院ID");
        }
        User user = userService.login(req.getUsername(), req.getPassword(), req.getNursingHomeId());
        if (user == null) {
            // 包含：用户名/密码错误、养老院不存在或停用、用户不属于该养老院等情况
            return Result.error("登录失败：请检查用户名、密码或养老院选择");
        }
        // 登录成功不返回用户信息
        //生成jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey().getBytes(StandardCharsets.UTF_8),//密钥
                jwtProperties.getUserTtl(), //过期时间
                claims
        );

        UserLoginDTO userLoginDTO = UserLoginDTO.builder()
                .token(token)
                .userDTO(
                        UserDTO.builder()
                                .id(Math.toIntExact(user.getId()))
                                .username(user.getUsername())
                                .real_name(user.getRealName())
                                .email(user.getEmail())
                                .build()
                )
                .build();

        return Result.success(userLoginDTO);
    }

    @PostMapping("/register")
    public Result<User> register(@RequestBody RegisterRequest req) {
        if (req == null || isBlank(req.getUsername()) || isBlank(req.getPassword()) || req.getNursingHomeId() == null) {
            return Result.error("参数不完整：请提供用户名、密码和养老院ID");
        }
        boolean ok = userService.register(req.getUsername(), req.getPassword(), req.getNursingHomeId());
        if (!ok) {
            return Result.error("注册失败：养老院无效或用户名已存在");
        }
        // 注册成功不返回用户信息
        return Result.success();
    }

    @PostMapping("/reset-password")
    public Result<Void> resetPassword(@RequestBody ResetPasswordRequest req) {
        if (req == null || isBlank(req.getUsername()) || isBlank(req.getEmail()) || isBlank(req.getPassword())) {
            return Result.error("参数不完整：请提供用户名、邮箱和新密码");
        }
        boolean ok = userService.resetPassword(req.getUsername(), req.getEmail(), req.getPassword());
        if (!ok) {
            return Result.error("重置失败：用户名与邮箱不匹配");
        }
        return Result.success();
    }
    private boolean isBlank(String s) {
        return s == null || s.trim().isEmpty();
    }
}
